package com.gree.elasticsearch.security.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.gree.elasticsearch.security.exception.JwtEmptyException;
import com.gree.elasticsearch.security.exception.JwtExpiredException;
import com.gree.elasticsearch.util.ResponseUtil;
import io.jsonwebtoken.Jwt;
import io.jsonwebtoken.SignatureException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 总有刁民想害朕，请叫我小花狗
 * create by zxw on 2020/5/30
 */
@Component(value = "customerAuthenticationFailureHandler")
public class CustomerAuthenticationFailureHandler implements AuthenticationFailureHandler {

    private Logger log = LoggerFactory.getLogger(CustomerAuthenticationFailureHandler.class.getName());

    private final String authenticationErrorMsg = "username or password error";

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        log.debug("authentication failure");
        ObjectMapper objectMapper = new ObjectMapper();

        response.setStatus(HttpStatus.UNAUTHORIZED.value());
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);

        if (exception instanceof BadCredentialsException) {
            log.debug("密码错误");
            objectMapper.writeValue(response.getWriter(), ResponseUtil.unAuthentication());
        } else if (exception instanceof JwtExpiredException) {
            log.debug("jwt失效");
            objectMapper.writeValue(response.getWriter(), ResponseUtil.unAuthentication());
        } else if (exception instanceof Jwt) {
            log.debug("jwt");
            objectMapper.writeValue(response.getWriter(), ResponseUtil.unAuthentication());
        } else if (exception instanceof JwtEmptyException) {
            log.debug("jwt is empty. error message is {}", exception.getMessage());
            objectMapper.writeValue(response.getWriter(), ResponseUtil.unAuthentication());
        }
    }
}
